from itsdangerous import TimedJSONWebSignatureSerializer as TJSSerializer, BadData
from django.conf import settings


def generate_save_user_token(openid):
    """对openid进行加密"""
    # 1.创建序列化器
    serializer = TJSSerializer(settings.SECRET_KEY, 600)

    # 2.包装要加密的数据
    data = {
        'openid': openid
    }

    # 3.dumps进行加密(返回默认是bytes类型)
    access_token_bytes = serializer.dumps(data)

    return access_token_bytes.decode()


def check_save_user_token(access_token):
    """解密"""
    # 1.创建序列化器
    serializer = TJSSerializer(settings.SECRET_KEY, 600)

    # 2.反序列化解密
    try:
        data = serializer.loads(access_token)
    except BadData:
        return None
    else:
        return data.get('openid')